<!-- 信息中心 -->
<template>
	<view class="practice-page">
		<!-- 顶部背景图 -->
		<view class="header-bg">
			<u-swiper :list="list.banner" keyName="image" showTitle :autoplay="true" :interval="3000" :duration="500"
				:height="state.swiperHeight + 'px'" imgMode="aspectFit" circular @click="clickWwiper"></u-swiper>
		</view>

		<!-- 功能入口 -->
		<view class="function-grid">
			<view class="grid-item" v-for="item in list.functions" :key="item.id" @click="navigateTo(item)">
				<view>
					<view class="name" :style="{
              color:
                formData.news_class_id == item.id ? 'red !important' : 'none',
              background: formData.news_class_id == item.id ? 'white' : 'none',
              padding: formData.news_class_id == item.id ? '10px' : '5px',
              borderRadius: formData.news_class_id == item.id ? '5px' : 'none',
            }">{{ item.class_name }}</view>
				</view>
			</view>
		</view>

		<!-- 资讯列表 -->
		<view class="news-list" v-if="list.functionsNews_is == 1">
			<view class="section-title">
				<text class="text">{{ title }}列表</text>
				<!-- <text class="time">02:48</text>
        <text class="views">238</text> -->
			</view>
						<scroll-view class="query_content" @scrolltolower="buttonScrolltolower" scroll-y="true"
							style="height: calc(55vh)">
							<u-empty mode="data" text="暂无数据" v-if="dataList.length == 0" marginTop="10vh"
								:icon="getResource('img/phone/mini/no_data.png')" />
							<view class="news-item" v-for="(item, index) in dataList" :key="index"
								@click="navigateToDetail(item.id)">
								<view class="news-content">
									<view class="news-title">{{ item.title }}</view>
									<view class="news-meta">
										<text class="source">{{ item.short_content }}</text>
									</view>
									<view class="news-meta">
										<text class="time">{{ item.created_at_show }}</text>
										<text class="views">{{ item.view_count }}</text>
									</view>
								</view>
								<view class="news-image">
									<I-Images :src="item.cover_show" width="100%" height="auto" lazyLoad :mode="aspectFill"
										showLoading showError fade duration="800" bgColor="#fff">
									</I-Images>
								</view>
							</view>
						</scroll-view>
		</view>
		<view class="news-list" style="padding: 0">
			<LiuYan v-if="list.functionsNews_is == 'liuyan'" />
			<ZhaoPin v-if="list.functionsNews_is == 'zhaopin'" />
		</view>
		<view class="tabbar">
			<Tabbar :index="3"></Tabbar>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		toRefs
	} from "vue";
	import {
		getNewsType,
		getNewsList
	} from "@/api/news.js";
	import {
		getBanner
	} from "@/api/userInfo.js";
	import {
		onShow,
		onUnload
	} from "@dcloudio/uni-app";
	import {
		getResource
	} from "../../utils/Resource.js";
	import {
		showLoading,
		showToast
	} from "@/utils/toast";

	import LiuYan from "./component/LiuYan.vue";
	import ZhaoPin from "./component/ZhaoPin.vue";

	const state = reactive({
		dataList: [],
		swiperHeight: "",
		swiperList: [{
				image: "https://uviewui.com/swiper/swiper2.png",
				title: "昨夜星辰昨夜风，画楼西畔桂堂东",
			},
			{
				image: "https://uviewui.com/swiper/swiper1.png",
				title: "身无彩凤双飞翼，心有灵犀一点通",
			},
			{
				image: "https://uviewui.com/swiper/swiper3.png",
				title: "谁念西风独自凉，萧萧黄叶闭疏窗，沉思往事立残阳",
			},
		],
		list: {
			functionsNews_is: null,
			functions: [{
					id: 1,
					class_name: "招标",
					status: 1,
					news_is: 1,
					created_at: "2025-09-13 15:35:20",
					status_name: "游客",
				},
				{
					id: 2,
					class_name: "找人",
					status: 1,
					news_is: "zhaopin",
					created_at: "2025-09-13 15:35:28",
					status_name: "游客",
				},
				{
					id: 3,
					class_name: "留言",
					status: 1,
					news_is: "liuyan",
					created_at: "2025-09-13 15:35:37",
					status_name: "游客",
				},
				{
					id: 5,
					class_name: "资讯",
					status: 1,
					news_is: 1,
					created_at: "2025-09-13 15:35:50",
					status_name: "游客",
				},
				{
					id: 6,
					class_name: "数据",
					status: 1,
					news_is: 1,
					created_at: "2025-09-13 15:35:57",
					status_name: "游客",
				},
				{
					id: 7,
					class_name: "政策",
					status: 1,
					news_is: 1,
					created_at: "2025-09-13 15:36:06",
					status_name: "游客",
				},
			],
			banner: [],
		},
		title: "",
		formData: {
			count: 0,
			page_no: 1,
			page_size: 10,
			page_count: 1,
			news_class_id: null,
		},
	});
	const {
		list,
		dataList,
		formData,
		title,
		swiperList
	} = toRefs(state);

	// 导航方法
	const navigateTo = async (path) => {
		title.value = path.class_name;
		state.list.functionsNews_is = path.news_is;
		formData.value.news_class_id = path.id;
		storage.set("currentFunctionState", {
			functionsNews_is: path.news_is,
			news_class_id: path.id,
			title: path.class_name,
		});

		if (path.news_is == 1) {
			dataList.value = [];
			await init();
		}
	};

	const navigateToDetail = (id) => {
		uni.navigateTo({
			url: `/pages_index/news/component/detail?id=${id}`
		});
	};

	const clickWwiper = (e) => {
		const currentBanner = list.value.banner[e];
		uni.navigateTo({
			url: currentBanner.url,
		});
	};
	const init = async () => {
		try {
			const res = await getNewsList(formData.value);
			// console.log(res);
			formData.value.count = res.data.count;
			formData.value.page_no = res.data.page_no;
			formData.value.page_size = res.data.page_size;
			formData.value.page_count = res.data.page_count;
			// console.log(formData.value);

			dataList.value = [...dataList.value, ...res.data.list];
		} catch (error) {}
	};
	onUnload(async () => {
		uni.removeStorageSync("currentFunctionState");
	});
	onShow(async () => {
		try {
			const cachedFunctionState = storage.get("currentFunctionState");
			if (cachedFunctionState) {
				// 本地有缓存：直接赋值，无需重新调用navigateTo
				title.value = cachedFunctionState.title;
				state.list.functionsNews_is = cachedFunctionState.functionsNews_is;
				formData.value.news_class_id = cachedFunctionState.news_class_id;
			} else {
				// 本地无缓存：默认显示第一个功能（原逻辑）
				await navigateTo(list.value.functions[0]);
			}

			const systemInfo = uni.getSystemInfoSync();
			const screenWidth = systemInfo.windowWidth;
			state.swiperHeight = screenWidth * 0.4875; // 按比例计算高度
			const res = await getBanner("5");
			// console.log(res);
			// list.value.banner = res.data;
			list.value.banner = res.data.map((item) => ({
				// 轮播图图片地址（根据接口返回的cover字段拼接完整URL）
				image: item.img_show,
				id: item.id,
				title: item.title,
				url: `/pages_index/news/component/detail?id=${item.id}`,
				type: "image",
			}));
			// console.log(list.value.banner);
		} catch (error) {}
		// await init();
	});

	const buttonScrolltolower = async () => {
		if (formData.value.count != dataList.value.length) {
			formData.value.page_no++;
			showLoading("加载中");
			await init();
		} else {
			showToast("已经最后一页了~");
		}
	};
	// 封装：本地存储工具（存/取/删）
	const storage = {
		// 存数据（key：键名，data：数据，expireHours：过期时间（小时），默认24小时）
		set: (key, data, expireHours = 24) => {
			const value = {
				data,
				expireTime: Date.now() + expireHours * 60 * 60 * 1000, // 过期时间戳
			};
			uni.setStorageSync(key, value);
		},
		// 取数据（key：键名，返回null表示过期或无数据）
		get: (key) => {
			const value = uni.getStorageSync(key);
			if (!value) return null;
			// 检查是否过期
			if (value.expireTime < Date.now()) {
				uni.removeStorageSync(key); // 过期则删除缓存
				return null;
			}
			return value.data;
		},
		// 删数据
		remove: (key) => uni.removeStorageSync(key),
	};
</script>

<style lang="scss" scoped>
	.practice-page {
		// padding-bottom: 100rpx;
		background-color: #f8f8f8;
	}

	.header-bg {
		position: relative;
		// height: 320rpx;
		// height: 25vh;
		overflow: hidden;

		.bg-image {
			width: 100%;
			height: 100%;
		}

		.header-content {
			position: absolute;
			bottom: 40rpx;
			left: 0;
			right: 0;
			padding: 0 30rpx;
			color: #fff;
			text-align: center;

			.title {
				font-size: 36rpx;
				font-weight: bold;
				margin-bottom: 10rpx;
				text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.5);
			}

			.subtitle {
				font-size: 24rpx;
				text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.5);
			}
		}
	}

	.news-list {
		background-color: #fff;
		padding: 0 20rpx;

		.section-title {
			display: flex;
			align-items: center;
			padding: 20rpx 0;
			border-bottom: 1rpx solid #eee;

			.text {
				font-size: 36rpx;
				font-weight: 700;
				color: #333;
				margin-right: 20rpx;
			}

			.time,
			.views {
				font-size: 24rpx;
				color: #999;
				margin-right: 20rpx;

				&::before {
					content: "·";
					margin-right: 5rpx;
				}
			}
		}

		.news-item {
			display: flex;
			padding: 20rpx 0;
			border-bottom: 1rpx solid #f5f5f5;

			.news-content {
				flex: 1;
				padding-right: 20rpx;

				.news-title {
					font-size: 30rpx;
					color: #333;
					margin-bottom: 15rpx;
					line-height: 1.4;
				}

				.news-meta {
					display: flex;
					align-items: center;
					font-size: 24rpx;
					color: #999;

					.source {
						margin-right: 20rpx;
					}

					.time,
					.views {
						margin-right: 20rpx;

						&::before {
							content: "·";
							margin-right: 5rpx;
						}
					}
				}
			}

			.news-image {
				width: 160rpx;
				height: 160rpx;
				border-radius: 8rpx;
				overflow: hidden;

				image {
					width: 100%;
					height: 100%;
				}
			}
		}
	}

	.tab-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		height: 100rpx;
		background-color: #fff;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
		z-index: 999;

		.tab-item {
			flex: 1;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;

			.icon {
				width: 44rpx;
				height: 44rpx;
				margin-bottom: 6rpx;
			}

			.text {
				font-size: 22rpx;
				color: #666;
			}

			&.active .text {
				color: #2979ff;
			}
		}
	}

	// 横向滚动容器
	.function-scroll {
		width: 100%;
		padding: 0 20rpx; // 左右留出边距
		box-sizing: border-box;
	}

	.function-grid {
		display: flex;
		align-items: center;
		justify-content: space-around;
		// 移除 justify-content: space-around（避免项目分散）
		padding: 10px 0;
		background-color: #f8f8f8; // 与页面背景一致
		white-space: nowrap; // 防止换行

		.grid-item {
			display: inline-flex; // 确保横向排列
			flex-direction: column;
			align-items: center;
			text-align: center;
			margin: 0 15rpx; // 项目之间的间距
			// min-width: 100rpx; // 固定最小宽度，避免内容挤压
			// min-width: ; // 固定最小宽度，避免内容挤压

			.name {
				font-size: 30rpx;
				font-weight: bold;
				color: #333;
			}
		}
	}
</style>